package org.znxs.comfriend.activities;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.android.material.floatingactionbutton.FloatingActionButton;

import org.znxs.comfriend.R;
import org.znxs.comfriend.adapters.ImageListAdapter;
import org.znxs.comfriend.models.User;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;


public class ProfilePreviewActivity extends AppCompatActivity {

    private RecyclerView rvImageList;
    private FloatingActionButton fabUploadImage;
    private ImageListAdapter adapter;
    private User user;

    private static final String IMAGE_DIR_NAME = "uploaded_images";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_profile_preview);

        // 初始化视图
        rvImageList = findViewById(R.id.rv_image_list);
        fabUploadImage = findViewById(R.id.fab_upload_image);

        // 获取传递的 User 对象
        Intent intent = getIntent();
        user = (User) intent.getSerializableExtra("user");

        if (user == null) {
            user = new User(); // 如果未传递 User 对象，则创建一个新的
        }

        // 设置图片列表适配器
        adapter = new ImageListAdapter(this, user.getImages());
        rvImageList.setLayoutManager(new GridLayoutManager(this, 3)); // 3列布局
        rvImageList.setAdapter(adapter);

        // 设置悬浮按钮的点击事件
        fabUploadImage.setOnClickListener(v -> openImagePicker());
    }

    // 打开图片选择器
    private void openImagePicker() {
        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(intent, 100); // 请求码为 100
    }

    // 处理图片选择结果
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == 100 && resultCode == RESULT_OK && data != null) {
            Uri selectedImageUri = data.getData();
            if (selectedImageUri != null) {
                List<String> images = user.getImages();

                // 假设我们要上传的是第一张图作为封面图，或者根据 position 控制
                int targetIndex = 0; // 示例：替换第一张图作为封面图
                String targetFileName = "image_" + targetIndex + ".png"; // 固定文件名

                // 获取旧路径（如果已存在）
                if (targetIndex < images.size()) {
                    String oldImagePath = images.get(targetIndex);
                    deleteOldImage(oldImagePath); // 删除旧文件
                }

                // 保存新图片到本地
                String newImagePath = saveImageToLocal(selectedImageUri, targetFileName);
                if (newImagePath == null) {
                    Toast.makeText(this, "图片保存失败", Toast.LENGTH_SHORT).show();
                    return;
                }

                // 更新或添加图片路径
                if (targetIndex < images.size()) {
                    images.set(targetIndex, newImagePath); // 替换已有路径
                } else {
                    images.add(newImagePath); // 添加新的路径
                }

                // 更新适配器
                adapter.notifyDataSetChanged();
            }
        }
    }

    // 获取图片的真实路径
    private String getRealPathFromURI(Uri contentUri) {
        String[] proj = {MediaStore.Images.Media.DATA};
        Cursor cursor = getContentResolver().query(contentUri, proj, null, null, null);
        if (cursor != null) {
            int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
            String path = cursor.getString(columnIndex);
            cursor.close();
            return path;
        }
        return null;
    }


    // 保存图片到本地，并返回文件路径
    private String saveImageToLocal(Uri uri, String targetFileName) {
        try {
            Context context = this;
            InputStream inputStream = getContentResolver().openInputStream(uri);
            if (inputStream == null) return null;

            // 创建目标目录
            File imageDir = new File(context.getFilesDir(), IMAGE_DIR_NAME);
            if (!imageDir.exists()) {
                imageDir.mkdirs();
            }

            // 创建目标文件
            File file = new File(imageDir, targetFileName);
            FileOutputStream outputStream = new FileOutputStream(file);

            byte[] buffer = new byte[1024];
            int length;
            while ((length = inputStream.read(buffer)) > 0) {
                outputStream.write(buffer, 0, length);
            }

            outputStream.close();
            inputStream.close();

            return file.getAbsolutePath();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    // 删除指定路径的图片
    private void deleteOldImage(String oldPath) {
        if (oldPath == null || oldPath.isEmpty()) return;

        File oldFile = new File(oldPath);
        if (oldFile.exists()) {
            oldFile.delete();
        }
    }
}